from kafka import KafkaProducer
from kafka.errors import KafkaError

# 指定Kafka服务器地址和端口号
bootstrap_servers = '124.221.66.3:9092'

# 创建Kafka生产者对象
producer = KafkaProducer(bootstrap_servers=bootstrap_servers)

# 指定要发送到的主题名称
topic = "my_topic"

# 构造要发送的消息内容
message = b"Hello, World!"

# 打印你好
print("Hello, World!")

# 发送消息到指定主题
future = producer.send(topic, message)

# 等待消息被成功发送或超时
try:
    record_metadata = future.get()
except Exception as e:
    print("Failed to send message:", str(e))
else:
    print("Message sent successfully!")

# 关闭Kafka生产者连接
producer.close()